package com.hqyj.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 统一异常处理
 * @Autor 伍军
 * @Date 2022/6/24 9:25
 * @Version 1.0
 **/
@RestControllerAdvice(basePackages ="com.hqyj.controller")
@Slf4j
public class ExceptionControllerAdvice {
    /**
     * 参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(ParamValidException.class)
    public R ExceptionAdvice( ParamValidException ex ) {
        log.info("参数校验异常:");
        //获取验证结果对象
        BindingResult br = ex.getBindingResult();

        String info = null;
        //取出提示信息
        for (ObjectError error : br.getAllErrors()) {
            info = error.getDefaultMessage();
            break;
        }
        return R.error(info,CodeEnum.ERROR_PARAM.CODE,"error");
    }
    /**
     * 空指针异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public R ExceptionAdvice( NullPointerException ex ) {
        log.info("空指针异常:");
        ex.printStackTrace();
        return R.error(CodeEnum.ERROR_SYS.MSG,CodeEnum.ERROR_SYS.CODE,"空指针异常");
    }

}







